﻿using MediatR;
using SmartCity.ProcessEngine.API.Write.Application.Commands.Settings;
using SmartCity.ProcessEngine.Domain;
using SmartCity.ProcessEngine.Errorcode;
using SmartCity.ProcessEngine.Infrastructure.Extensions;
using SmartCity.ProcessEngine.Infrastructure.Interfaces;

namespace SmartCity.ProcessEngine.API.Write.Application.CommandHandlers.Settings
{
    /// <summary>
    /// 流程设置创建命令处理
    /// </summary>
    public class SettingCreateCommandHandler : IRequestHandler<SettingCreateCommand, ApiResult<int>>
    {
        /// <summary>
        /// 流程设置仓储
        /// </summary>
        private readonly IBaseRepository<WF_Setting> settingRep;
        private readonly ILogger<SettingCreateCommandHandler> logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="settingRep"></param>
        public SettingCreateCommandHandler(IBaseRepository<WF_Setting> settingRep,ILogger<SettingCreateCommandHandler> logger)
        {
            this.settingRep = settingRep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiResult<int>> Handle(SettingCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.code = ApiEnum.AddSuccess;
            result.message = ApiEnum.AddSuccess.GetDescription();

            using(var tran = settingRep.DB.Database.BeginTransaction())
            {
                try
                {
                    if(request.settings.Count == 0)
                    {
                        throw new Exception("流程设置的数据至少需要两条数据");
                    }
                    //查询旧的
                    var list = settingRep.GetAll().Where(x => x.FormNo == request.settings[0].FormNo).ToList();
                    //更新旧的
                    list.ForEach(x =>
                    {
                        x.IsDeleted = true;
                    });
                    await settingRep.UpdateRangeAsync(list);
                    //添加新的
                    await settingRep.AddRangeAsync(request.settings);

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogError("保存流程设置报错:" + ex.Message);
                    result.code = ApiEnum.AddFail;
                    result.message = ApiEnum.AddFail.GetDescription();
                    tran.Rollback();
                }
            }

            return await Task.FromResult(result);
        }
    }
}
